//
//  UATApi.m
//  Pods-UStarter_Example
//
//  Created by Mark on 2021/1/7.
//

#import "UATApi.h"
#import "UATStarter.h"
#import <AFNetworking/AFNetworking.h>
@implementation UATApi

+ (nullable UATRequestConfig*)getConfig {
    return [[UATStarter shareInstance] requestConfig];;
}

+ (AFHTTPSessionManager*)session {
    AFHTTPSessionManager * sess =[AFHTTPSessionManager manager];
    sess.requestSerializer = [AFJSONRequestSerializer serializer];
    sess.responseSerializer= [AFJSONResponseSerializer serializer];
    sess.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    return sess;
}

+ (void) doGetAction:(NSString *)action withParam:(NSDictionary *)param callback:(UATApiRequestCallback)cb {
    
    UATRequestOption * opt = [[UATApi getConfig] toOptWithAction:action param:param data:@{}];
    
    [[UATApi session] GET:opt.url parameters:nil headers:opt.header progress:^(NSProgress * _Nonnull downloadProgress) {
            cb(UATApiRequestStatusDOING,nil,downloadProgress,nil,nil);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            cb(UATApiRequestStatusSUCCESS,responseObject,nil,task,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            cb(UATApiRequestStatusFAIL,nil,nil,task,error);
        }];
    
}


+ (void) doPostJsonAction:(NSString *)action withParam:(NSDictionary *)param withData:(NSDictionary *)data callback:(UATApiRequestCallback)cb {
    UATRequestOption * opt = [[UATApi getConfig] toOptWithAction:action param:param data:data];
    [[UATApi session] POST:opt.url parameters:opt.data headers:opt.header progress:^(NSProgress * _Nonnull uploadProgress) {
            cb(UATApiRequestStatusDOING,nil,uploadProgress,nil,nil);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            cb(UATApiRequestStatusSUCCESS,responseObject,nil,task,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            cb(UATApiRequestStatusFAIL,nil,nil,task,error);
        }];
}

+ (void) doPostFormDataAction:(NSString *)action withParam:(nullable NSDictionary *)param withData:(nonnull NSDictionary *)data cb:(nonnull UATApiRequestCallback)cb {
    UATRequestOption * opt = [[UATApi getConfig] toOptWithAction:action param:param data:data];
    [[UATApi session] POST:opt.url parameters:nil headers:opt.header constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSString*k in opt.data) {
            [formData appendPartWithFormData:[[opt.data objectForKey:k] dataUsingEncoding:NSUTF8StringEncoding] name:k];
        }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            cb(UATApiRequestStatusDOING,nil,uploadProgress,nil,nil);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            cb(UATApiRequestStatusSUCCESS,responseObject,nil,task,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            cb(UATApiRequestStatusFAIL,nil,nil,task,error);
        }];
}

+ (void) doPutAction:(NSString *)action withParam:(NSDictionary *)param withData:(NSDictionary *)data callback:(UATApiRequestCallback)cb{
    UATRequestOption * opt = [[UATApi getConfig] toOptWithAction:action param:param data:data];
    [[UATApi session] PUT:opt.url parameters:opt.data headers:opt.header success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            cb(UATApiRequestStatusSUCCESS,responseObject,nil,task,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            cb(UATApiRequestStatusFAIL,nil,nil,task,error);
        }];
}

+ (void) doDeleteAction:(NSString *)action withParam:(NSDictionary *)param withData:(NSDictionary *)data callback:(UATApiRequestCallback)cb {
    UATRequestOption * opt = [[UATApi getConfig] toOptWithAction:action param:param data:data];
    [[UATApi session] DELETE:opt.url parameters:opt.data headers:opt.header success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            cb(UATApiRequestStatusSUCCESS,responseObject,nil,task,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            cb(UATApiRequestStatusFAIL,nil,nil,task,error);
        }];
}

+ (void) downloadAction:(NSString *)action
              withParam:(NSDictionary *)param
                   data:(NSDictionary *)data
                     cb:(UATApiRequestCallback)cb{
    [UATApi downloadAction:action withParam:param data:data destination:@"" cb:cb];
}

/// 下载到指定位置
+ (void) downloadAction:(NSString*)action
              withParam:(nullable NSDictionary*)param
                   data:(nullable NSDictionary*)data
            destination:(NSString*)destination
                     cb:(UATApiRequestCallback)cb;{
    [UATApi downloadAction:action withParam:param data:data destination:destination rename:nil cb:cb];
}

/// 下载到指定位置并且重命名
+ (void) downloadAction:(NSString*)action
              withParam:(nullable NSDictionary*)param
                   data:(nullable NSDictionary*)data
            destination:(nullable NSString*)destination
                 rename:(nullable NSString*)rename
                     cb:(UATApiRequestCallback)cb;{
    [UATApi downloadAction:action withParam:param data:data dict:NSDocumentationDirectory destination:destination rename:rename cb:cb];
}

/// 下载文件到指定路径【支持重命名】
/// @param action 下载地址
/// @param param url请求参数
/// @param data 固定为nil
/// @param searchPathDomainMask 下载到的目标路径【文档、缓存】
/// @param destination 相对路径，【注意：不要斜杆开头,需要斜杆结尾】
/// @param rename 别名
/// @param cb 回调事件
+ (void) downloadAction:(NSString *)action
              withParam:(NSDictionary *)param
                   data:(NSDictionary *)data
                   dict:(NSSearchPathDirectory)dict
            destination:(nonnull NSString *)destination
                 rename:(nonnull NSString*)rename
                     cb:(UATApiRequestCallback)cb {
    
    UATRequestOption * opt = [[UATApi getConfig] toOptWithAction:action param:param data:data];
    DLog(@"destination : %@",destination);
    NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:opt.url]];
    
    NSURLSessionDownloadTask*task=[[AFHTTPSessionManager manager] downloadTaskWithRequest:req progress:^(NSProgress * _Nonnull downloadProgress) {
        cb(UATApiRequestStatusDOING,nil,downloadProgress,nil,nil);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        NSURL *path = [[NSFileManager defaultManager] URLForDirectory:dict inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];

        NSURL * url = [path URLByAppendingPathComponent:destination];
        NSFileManager * fm = [NSFileManager defaultManager];
        if(![fm fileExistsAtPath:url.absoluteString]){
            [fm createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString * filename = rename == nil || [rename isEqual:@""] ? response.suggestedFilename : rename;
        return [url URLByAppendingPathComponent:filename];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        DLog("\ncomplete\n");
        DLog(@"%@",filePath);
        if(error!=nil){
            cb(UATApiRequestStatusFAIL,nil,nil,nil,error);
        }else{
            cb(UATApiRequestStatusSUCCESS,response,nil,nil,nil);
        }
    }];
    [task resume];
}


+ (AFHTTPSessionManager*)textSession{
    AFHTTPSessionManager * m = [AFHTTPSessionManager manager];

    m.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                         
                                                                         @"text/html",
                                                                         @"text/plain",

                                                                         @"image/jpeg",

                                                                         @"image/png",

                                                                         @"application/octet-stream",

                                                                         @"text/json",

                                                                         nil];
    m.requestSerializer = [AFHTTPRequestSerializer serializer];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    return m;
}

+ (void) uploadAction:(NSString *)action
            withParam:(NSDictionary *)param
                 data:(NSDictionary *)data
             fileData:(NSData *)fileData
              fileKey:(NSString *)fileKey
                   cb:(UATApiRequestCallback)cb{
    UATRequestOption * opt = [[UATApi getConfig] toOptWithAction:action param:param data:data];
    
    [[UATApi textSession] POST:opt.url
                    parameters:@{}
                       headers:opt.header
     constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//            [formData appendPartWithFormData:fileData name:fileKey];
        [formData appendPartWithFileData:fileData name:fileKey fileName:fileKey mimeType:@"*/*"];
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            cb(UATApiRequestStatusDOING,nil,uploadProgress,nil,nil);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString * str  = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            cb(UATApiRequestStatusSUCCESS,str,nil,task,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            cb(UATApiRequestStatusFAIL,nil,nil,task,error);
        }];
}

@end
